package com.tandashi.springbootstudy01.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tandashi.springbootstudy01.convention.constants.StringConst;
import com.tandashi.springbootstudy01.dto.opening.Kmh2024TargetCustStats;
import com.tandashi.springbootstudy01.service.es.ElasticService;
import com.tandashi.springbootstudy01.service.es.ElasticServiceBase;
import com.tandashi.springbootstudy01.util.QueryUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.MultiSearchRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.valuecount.ValueCountAggregationBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;

@Service
@Slf4j
public class Opening2024CustomerService {

    public Kmh2024TargetCustStats findKmh2024TargetCustStats(String agentCode, String tab, String source) {
        try {
            return getKmh2024TargetCustStats(agentCode, tab, source);
        } catch (Exception e) {
            log.error("opening2024CustomerService.getKmh2024TargetCustStats", e);
            return null;
        }
    }

    private Kmh2024TargetCustStats getKmh2024TargetCustStats(String agentCode, String tab, String source) throws IOException {
        MultiSearchRequest request = new MultiSearchRequest();
        request.add(countTotalReq(agentCode, tab, source));

        Map<String, Number> map = elasticService.aggSingleValue(request);
        Kmh2024TargetCustStats esStats = objectMapper.convertValue(map, Kmh2024TargetCustStats.class);
        return esStats;
    }

    private SearchRequest countTotalReq(String agentCode, String tab, String source) {
        BoolQueryBuilder queryBuilder = QueryBuilders
                .boolQuery()
                .filter(QueryBuilders.termQuery("agent_code.keyword", agentCode));

        if (StringConst.YES.equals(tab)) {
            QueryUtils.termQuery(queryBuilder, StringConst.YES, "if_tgt_cust");
        }

        QueryUtils.termQuery(queryBuilder, "gx", "due_agent_cate.keyword");

        ValueCountAggregationBuilder agg = AggregationBuilders.count("numTotal").field("customer_id.keyword");

        return ElasticServiceBase.buildAggRequest(kmh2024TargetCustomerDeatilIndex, queryBuilder, agg);
    }

    @Autowired
    private ElasticService elasticService;

    @Autowired
    private ObjectMapper objectMapper;

    @Value("${es.index.kmh.2024.target.cust.detail:2024kjz_tgt_cust_agent_detail}")
    private String kmh2024TargetCustomerDeatilIndex;
}
